package multithread.framework.xml;

import java.util.Iterator;
import java.util.List;

import multithread.framework.constant.XMLConfigConstant;
import multithread.framework.threadmethod.ThreadMethod;
import multithread.framework.threadmethod.ThreadMethodGroup;

import org.jdom.Element;

public class GroupElement extends Element implements IVerifiable {
	private static final long serialVersionUID = -3705610760605191219L;
	private Element methods;

	public GroupElement(String name, int type) {
		super(XMLConfigConstant.GROUP_ELEMENT);
		setAttribute(XMLConfigConstant.NAME_PROPERTY,
				name == null ? "virtual-group" : name);
		setAttribute(XMLConfigConstant.TYPE_PROPERTY, String.valueOf(type));
	}

	public GroupElement(ThreadMethodGroup methodGroup) {
		this(methodGroup.getThreadGroupFor() == null ? null : methodGroup
				.getThreadGroupFor().value(),
				XMLConfigConstant.THREAD_GROUP_FOR_TYPE);
		for (Iterator<ThreadMethod> it = methodGroup.iterator(); it.hasNext();) {
			addMethodElement(new MethodElement(it.next()));
		}
	}

	public Element addMethodElement(MethodElement methodElement) {
		if (methodElement != null && methodElement.validate()) {
			synchronized (this) {
				if (methods == null) {
					methods = new Element(XMLConfigConstant.MEHTODS_ELEMENT);
					addContent(methods);
				}
			}
			return methods.addContent(methodElement);
		}
		return null;
	}

	/**
	 * check the group element is validation
	 * 
	 * @return true or false
	 */
	public boolean validate() {
		List<?> childlist = this.getChildren();
		return childlist == null ? false : childlist.size() > 0 ? true : false;
	}

}